﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Globalization;
using System.Text;

namespace Vit.Data
{
    public class CommandExecutionEventArgs : System.ComponentModel.CancelEventArgs
    {
        internal CommandExecutionEventArgs(DbCommandWrapper command, string method)
        {
            this.Command = command;
            this.Method = method;
        }

        /// <summary>
        /// Gets the command object.
        /// </summary>
        /// <value>The command.</value>
        public DbCommandWrapper Command { get; private set; }

        /// <summary>
        /// Gets the method which caused command execution (ExecuteScalar, ExecuteQuery, ExecuteNonQuery).
        /// </summary>
        /// <value>The method name.</value>
        public string Method { get; private set; }

        /// <summary>
        /// Gets the execution status.
        /// </summary>
        /// <value>Execution status.</value>
        public CommandExecutionStatus Status { get; internal set; }

        /// <summary>
        /// Gets the command result.
        /// </summary>
        /// <value>The command result.</value>
        public object Result { get; internal set; }

        /// <summary>
        /// Gets the time it took to execute the command.
        /// </summary>
        /// <value>The duration.</value>
        public TimeSpan Duration { get; internal set; }

        /// <summary>
        /// Returns textual dump of the command suitable for putting in a log file.
        /// </summary>
        /// <returns>Textual dump of the command including command text and parameters, 
        /// suitable for putting in a log file.</returns>
        public string ToTraceString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(this.Command.CommandText);

            foreach (DbParameter par in this.Command.Parameters)
            {
                sb.AppendFormat(
                    CultureInfo.InvariantCulture,
                    "\r\n-- {0} (dbtype={1}, size={4}, direction={2}) = {3}",
                    par.ParameterName,
                    par.DbType,
                    par.Direction,
                    par.Value as string ?? "null",
                    par.Size);
            }

            return sb.ToString();
        }
    }
}
